<?php

namespace Home\Logic;

/**
 * 支付逻辑
 */
class PayLogic
{

    public $redis;

    public function __construct()
    {
        $this->redis = new \Predis\Client(C('REDIS'), ['prefix' => C('REDIS_PREFIX')]);
    }

    /**
     * 测试店铺防卡单 (花呗)
     * @param int $id 店铺id
     */
    public static function huabeitest($id,$qrpay)
    {
        if (empty($id)) {
            $data = ['code' => 0, 'msg' => '没有可用的店铺', 'data' => ''];
            return $data;
        }

        $kbsh = M('kbsh')->find($id);
        $toAccount = D('Adata')->where(['id' => 1])->find();//平台收款支付宝，用户提现

//        Vendor('dangmianfu_demo_php.f2fpay.qrpay_test');
//        $qrpay = new \Alipay;

        $royalty_parameters = [
            'trans_out' => "{$kbsh['user_id']}",//分账出去的user_id 分账支出方账户，类型为userId，本参数为要分账的支付宝账号对应的支付宝唯一用户号。以2088开头的纯16位数字。
            'trans_in' => $toAccount['t_account'], //合作伙伴id 分账收入方账户，类型为userId，本参数为要分账的支付宝账号对应的支付宝唯一用户号。以2088开头的纯16位数字。
            'amount' => 0.01,   //分账出去的金额
            'desc' => '测试店铺防卡单'
        ];
        $app_auth_token = '';
        $out_request_no = date("Ymd") . rand(1000000000, 9999999999);  //分账流水号

        //店铺的订单
//        $dingdan_ids = M('dingdan')->where(['seller_id' =>$kbsh['user_id'] ])->getField('id',true);
//        if(empty($dingdan_ids)) $data = ['code' => -1,'msg' => '新上接口请先付款一笔再进行测试','data' => ''];
//
//        $randkey = array_rand($dingdan_ids);
//        $randid = $dingdan_ids[$randkey];
//        //随机取出支付宝交易号
//        $trade_no = M('dingdan')->where(['id' => $randid])->getField('trade_no');
        //获取测试订单
        $trade_no = self::getTestOrder($kbsh['user_id'],$danhao);

        $result = $qrpay->settle($out_request_no, $trade_no, $royalty_parameters, $app_auth_token, $kbsh);

        $resultCode = $result->code;
        if (!empty($resultCode) && $resultCode == 10000) {
            $data = [
                'code' => 1,
                'msg' => '分账成功',
                'data' => ''
            ];
        } else {
            D('Kbsh')->where(['id' => $id])->save(['use_status' => 0, 'cause' => $result->sub_msg . '//余额关闭', 'money' => 0.01]);
            $data = [
                'code' => 0,
                'msg' => '分账失败',
                'data' => $result
            ];
        }
        return $data;
    }

    /**
     * 测试店铺防卡单 (信用卡)
     * @param int $id 手机网站支付id
     */
    public static function xyktest($id, $danhao,$qrpay)
    {
        if (empty($id)) {
            $data = ['code' => 0, 'msg' => '没有可用的店铺', 'data' => ''];
            return $data;
        }

        $kbsh = M('alipays')->find($id);
        $toAccount = D('Adata')->where(['id' => 1])->find();//平台收款支付宝，用户提现

//        Vendor('dangmianfu_demo_php.f2fpay.qrpay_test');
//        $qrpay = new \Alipay;

        $royalty_parameters = [
            'trans_out' => "{$kbsh['pid']}",//分账出去的user_id 分账支出方账户，类型为userId，本参数为要分账的支付宝账号对应的支付宝唯一用户号。以2088开头的纯16位数字。
            'trans_in' => $toAccount['t_account'], //合作伙伴id 分账收入方账户，类型为userId，本参数为要分账的支付宝账号对应的支付宝唯一用户号。以2088开头的纯16位数字。
            'amount' => 0.01,   //分账出去的金额
            'desc' => '测试店铺防卡单'
        ];
        $app_auth_token = '';
        $out_request_no = date("Ymd") . rand(1000000000, 9999999999);  //分账流水号

        //店铺的订单
        $trade_no = self::getTestOrder($kbsh['pid'],$danhao);

        $result = $qrpay->settle($out_request_no, $trade_no, $royalty_parameters, $app_auth_token, $kbsh);

        $resultCode = $result->code;
        if (!empty($resultCode) && $resultCode == 10000) {
            $data = [
                'code' => 1,
                'msg' => '分账成功',
                'data' => ''
            ];

        } else {
            //下架手机网站支付店铺
            M('alipays')->where(['id' => $id])->save(['status' => 0, 'cause' => $result->sub_msg . '//余额关闭', 'money' => 0.01]);
            $data = [
                'code' => 0,
                'msg' => '分账失败',
                'data' => $result
            ];
        }
        return $data;
    }


    /**
     * 按序号获取花呗店铺
     * @return string
     */
    public static function getHb($alipay, $n = false)
    {
        if ($n !== false && $n == 0) {
            return;
        } else {
            $n--;
        }

        $redis = new \Predis\Client(C('REDIS'), ['prefix' => C('REDIS_PREFIX')]);
        $redis->rpoplpush('hbshoplist', 'hbshoplist');
        $id = $redis->lindex('hbshoplist', 0);

        if(empty($id)) return false;

        //防卡单开关
        $ptdata = M('ptdata')->find(1);
        if ($ptdata['hbfkd'] == 1) {

            $result = self::huabeitest($id,$alipay);
            file_put_contents("test.txt", date('Y-m-d H:i:s') . '测试店铺防卡单花呗结果：'.$n.'：' . json_encode($result) . PHP_EOL, FILE_APPEND);

            if ($result['code'] == 0) {
                $redis->lrem('hbshoplist', 1, $id);
                //递归
                self::getHb($alipay, $n);
            }else{
                file_put_contents("test.txt", date('Y-m-d H:i:s') . '测试店铺防卡单花呗成功'.$n.'：' . json_encode($result) . PHP_EOL, FILE_APPEND);
                return $id;
            }
        }

        return $id;
    }

    /***
     * 按序号获取信用卡店铺
     * @return string
     */
    public static function getXyk($qrpay,$danhao, $n = false)
    {
        if ($n !== false && $n == 0) {
            return;
        } else {
            $n--;
        }
        $redis = new \Predis\Client(C('REDIS'), ['prefix' => C('REDIS_PREFIX')]);
        $redis->rpoplpush('xykshoplist', 'xykshoplist');
        $id = $redis->lindex('xykshoplist', 0);

        if(empty($id)) return false;

        //防卡单开关
        $ptdata = M('ptdata')->find(1);
        if ($ptdata['hbfkd'] == 1) {

            //分账测试
            $result = self::xyktest($id,$danhao,$qrpay);

            file_put_contents("test.txt", date('Y-m-d H:i:s') . '测试店铺防卡单- (信用卡)结果'.$n.'：' . json_encode($result) . PHP_EOL, FILE_APPEND);

            if ($result['code'] == 0) {
                $redis->lrem('xykshoplist', 1, $id);
                //递归
                self::getXyk($qrpay,$danhao, $n);
            }else{
                file_put_contents("test.txt", date('Y-m-d H:i:s') . '测试店铺防卡单信用卡成功'.$n.'：' . json_encode($result) . PHP_EOL, FILE_APPEND);
                return $id;
            }
        }
        return $id;
    }

    /****************************/


    /**
     * 付款时按序号获取可用的店铺id
     * @param $alipay
     * @param int $type 通道类型：1=手机网站支付,2=当面付,4=手机网站支付花呗,5=当面付信用卡
     * @param bool $n
     * @return bool|string|void
     */
    public function getEnableDianpu($alipay, $type,$n = false)
    {
        if ($n !== false && $n == 0) {
            return;
        } else {
            $n--;
        }

        $this->redis =  new \Predis\Client(C('REDIS'),['prefix' => C('REDIS_PREFIX')]);
        $rediskey = self::getRedisKeyByType($type);

        $this->redis->rpoplpush($rediskey, $rediskey);
        $id = $this->redis->lindex($rediskey, 0);

        put_file('序号:' . $n.'付款时按序号获取可用的店铺id:',$id);

        if(empty($id)) {
            //递归
            return self::getEnableDianpu($alipay, $type,$n);
        }
//        if($type == 2) {
//            $kbsh = M('kbsh')->where(['handle_status' => 1,'use_status' => 1, 'status' => 1])->find();
//            if(!$kbsh) {
//                //递归
//                return self::getEnableDianpu($alipay, $type,$n);
//            }
//        }else{
//            $alipay = M('alipays')->where(['status' => 1])->find();
//            if(!$alipay) {
//                //递归
//                return self::getEnableDianpu($alipay, $type,$n);
//            }
//        }


        //防卡单开关
        $fkd = \Home\Model\PtdataModel::getFkdByType($type);
        if ($fkd == 1) {

            $result = $this->fangKaDan($id,$alipay,$type);
            file_put_contents("test.txt", date('Y-m-d H:i:s') . '测试店铺防卡单结果：'.$n.'：' . json_encode($result) . PHP_EOL, FILE_APPEND);

            if ($result['code'] == 0) {
//                $this->redis->lrem($rediskey, 1, $id);
                //递归
                return self::getEnableDianpu($alipay, $type,$n);
            }else{
//                file_put_contents("test.txt", date('Y-m-d H:i:s') . '测试店铺防卡单花呗成功'.$n.'：' . json_encode($result) . PHP_EOL, FILE_APPEND);
                return $id;
            }
        }

        put_file('序号:' . $n.'付款返回店铺id:',$id);
        return $id;

    }

    /**
     * 测试店铺防卡单
     * @param $id
     * @param object $alipay 支付宝对象
     * @param int $type 通道类型：1=手机网站支付,2=当面付,4=手机网站支付信用卡,5=当面付信用卡
     * @return array
     */
    public function fangKaDan($id,$alipay,$type)
    {
        if (empty($id)) {
            file_put_contents("test.txt", date('Y-m-d H:i:s') . '--该通道暂(' .$type . ')无可用的店铺--' . PHP_EOL, FILE_APPEND);

            $data = ['code' => 0, 'msg' => '该通道暂无可用的店铺', 'data' => ''];
            return $data;
        }

        if($type == 2){
            $dianpu = M('kbsh')->find($id);
            $trans_out = $dianpu['user_id'];
        }else{
            $dianpu = M('alipays')->find($id);
            $trans_out = $dianpu['pid'];
        }

        $toAccount = D('Adata')->where(['id' => 1])->find();//平台收款支付宝，用户提现
        $royalty_parameters = [
            'trans_out' => "{$trans_out}",//分账出去的user_id 分账支出方账户，类型为userId，本参数为要分账的支付宝账号对应的支付宝唯一用户号。以2088开头的纯16位数字。
            'trans_in' => $toAccount['t_account'], //合作伙伴id 分账收入方账户，类型为userId，本参数为要分账的支付宝账号对应的支付宝唯一用户号。以2088开头的纯16位数字。
            'amount' => 0.01,   //分账出去的金额
            'desc' => '店铺防卡单'
        ];

        $app_auth_token = '';
        $out_request_no = date("Ymd") . rand(1000000000, 9999999999);  //分账流水号

        //获取测试订单
        $trade_no = self::getTestOrder($trans_out,$type);

        $params = [
            'out_request_no' => $out_request_no,
            'trade_no' => $trade_no,
            'royalty_parameters' => $royalty_parameters,
            'dianpu' => $dianpu
        ];
        file_put_contents("test.txt", date('Y-m-d H:i:s') . '-fangKaDan参数--type:(' .$type . ' --id:  ' . $id  . ')--' . json_encode($params).PHP_EOL, FILE_APPEND);


        $result = $alipay->settle($out_request_no, $trade_no, $royalty_parameters, $app_auth_token, $dianpu);

        $resultCode = $result->code;
        if (!empty($resultCode) && $resultCode == 10000) {
            $data = [
                'code' => 1,
                'msg' => '防卡单分账成功',
                'data' => ''
            ];
            file_put_contents("test.txt", date('Y-m-d H:i:s') . '-防卡单分账成功--' . PHP_EOL, FILE_APPEND);

        } else {

            $payLogic = new \Home\Logic\PayLogic();
            $cause = $result->sub_msg . '//余额关闭';
            $payLogic->changeAlipayStatusByType($type,$id,2,$cause);

            $data = [
                'code' => 0,
                'msg' => '防卡单分账失败',
                'data' => $result
            ];
            file_put_contents("test.txt", date('Y-m-d H:i:s') . '-防卡单分账失败--' . PHP_EOL, FILE_APPEND);

        }
        return $data;
    }


    /**
     * 获取测试订单
     * @param int $seller_id 商户支付宝用户号，2088开头
     * @param int $type 类型：1=手机网站支付,2=当面付,4=手机网站支付花呗,5=当面付信用卡
     */
    public function getTestOrder($seller_id,$type)
    {
        $res  = M('test')->where(['seller_id' => $seller_id, 'status' => 1,'is_use' => ['lt',30],'type' => $type])->order('id desc')->find();

        if(!empty($res)){
//            echo 'test dan';
            M('test')->where(['id' => $res['id']])->setInc('is_use');
            $trade_no = $res['trade_no'];
        }else{
//            echo 'dingdan';
            //店铺的订单
            $dingdan_ids = M('dingdan')->where(['seller_id' =>$seller_id,'status' => 7 ,'pay_type' => $type,'fenzhang_status' => 1])->order('id desc')->getField('id',true);
            if(empty($dingdan_ids)) {
                $data = ['code' => -1,'msg' => '新上接口请先进行测试','data' => ''];
//                return $data;

                put_file('获取测试订单:新上接口请先进行测试',$data);
            }

            $randkey = array_rand($dingdan_ids);
            $randid = $dingdan_ids[$randkey];
            //随机取出支付宝交易号
            $trade_no = M('dingdan')->where(['id' => $randid])->getField('trade_no');
        }
        put_file('获取测试订单-支付宝交易号:',$trade_no);
        return $trade_no;
    }

    /**
     * 根据通道类型获取redis的key
     * @param int  $type 通道类型：1=手机网站支付,2=当面付,4=手机网站支付花呗,5=当面付信用卡
     */
    public static function getRedisKeyByType($type){
        if($type == 1){
            $key = "xykshoplist";
        }elseif($type == 2){
            $key = "hbshoplist";
        }elseif($type == 4){
            $key = "waphbshoplist";
        }elseif($type == 5){
            $key = "dmxykshoplist";
        }

        return $key;
    }

    /**
     * 根据通道获取支付宝账号资料
     * @param int $type 类型：1=手机网站支付,2=当面付,4=手机网站支付花呗,5=当面付信用卡
     */
    public function getAlipayByType($type,$id){
        if($type == 2){
            $one = M('kbsh')->find($id);
        }else{
            $one = M('alipays')->find($id);
        }
        return $one;
    }

    /**
     * 根据通道下架店铺
     * @param int $status 测试状态:0=未测试,1=正常,2=异常,user_status:使用状态:0=离线,1=在线
     *  @param int $type 类型：1=手机网站支付,2=当面付,4=手机网站支付花呗,5=当面付信用卡
     */
    public function changeAlipayStatusByType($type,$id,$status,$cause = ''){
        if($type == 2){
            //测试状态:0=未测试,1=正常,2=异常
            if($status == 1){
                $data = ['status' => $status, 'cause' => $cause];
                //当面付花呗 ，未审核不能上架
//                \Home\Logic\ShopLogic::addRedisShop(2,$id);

            }else{
                $data = ['status' => $status,'use_status' =>0,'handle_status' =>0, 'cause' => $cause];

                \Home\Logic\ShopLogic::delRedisShop($type,$id);

            }

            $one = M('kbsh')->where(['id' => $id])->save($data);
        }else{

            if($status == 1){
                \Home\Logic\ShopLogic::addRedisShop($type,$id);

            }else{
                \Home\Logic\ShopLogic::delRedisShop($type,$id);
            }
            $one = M('alipays')->where(['id' => $id])->save(['status' => $status, 'cause' => $cause]);
        }

    }

    /**
     * 自动回款，没分给客户情况下，自动从平台分账给客户
     * (单笔转账接口)
     */
    public static function autoHuiKuan($buyer_id,$amount,$user_id,$transfer){

        $remark = '平台自动回款给用户';


        $adata = D('Adata')->where(['id' => 1])->find();

        // 查看当日提现总金额  超过95万则使用另一个支付宝
        $time1 = strtotime(date("Ymd", strtotime("+1 day")));
        $time2 = strtotime(date("Ymd"));
        $money = D('Dingdan')->where("status=1 and pay_time between $time2 and $time1")->sum('pay_money');

        $payee_real_name = M('ptyh')->where(['uid' => $user_id])->getField('name');
        $payer_show_name = '绿叶收银台';

        $out_biz_no = date("YmdHis") . rand(100000, 999999);

        put_file('自动回款 转账参数：' , [
            'buyer_id' => $buyer_id,
            'amount' => $amount,
            'payee_real_name' => $payee_real_name,
            'payer_show_name' => $payer_show_name,
            'adata' => $adata


        ]);
//        $result = $transfer->transfer8($out_biz_no, $buyer_id, $amount, $remark, $payee_real_name, $payer_show_name, $adata);
        $result = $transfer->transferSingleUserAlipay($out_biz_no, $buyer_id, $amount, $remark, $payer_show_name, $adata);

        file_put_contents("hb.txt", date('Y-m-d H:i:s') . '自动回款结果：' . json_encode($result) . PHP_EOL, FILE_APPEND);

        if (empty($result->sub_msg) && $result->out_biz_no == $out_biz_no) {
            // 说明是成功的   1、提现状态修改 2、提现次数、用户余额修改


        } else {


        }
    }

    /**
     * 修改订单状态
     * @param int $id 订单id
     * @param int $status 订单状态:0=未支付,1=已支付,2=没分给平台,3=分给平台,4=没分给平台，分给客户,5=没分给平台，没分给客户，6=分给平台，没分给客户
     */
    public static function updateDingdanStatus($id,$status){
        M('dingdan')->where(['id' => $id])->save(['status' => $status]);
    }

    /**
     * 修改订单分账状态
     * @param $id
     * @param $status
     */
    public static function updateDingdanFenzhangStatus($id,$status){
        M('dingdan')->where(['id' => $id])->save(['fenzhang_status' => $status]);
    }




}